package com.zigong.app.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.utils.GroupOrderHelperSingled;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.ruihang.generalibrary.utils.TimeObserve;
import com.zigong.app.R;
import com.zigong.app.application.Cache;
import com.zigong.app.base.BaseActivity;
import com.zigong.app.beans.FocusColumn;
import com.zigong.app.beans.HomeListItem;
import com.zigong.app.beans.NewsDate;
import com.zigong.app.beans.NewsItem;
import com.zigong.app.beans.Titles;
import com.zigong.app.http.AbsListNetCallback;
import com.zigong.app.http.NetUtils;
import com.zigong.app.ui.activities.CommodityDetailActivity;
import com.zigong.app.ui.activities.LoginActivity;
import com.zigong.app.ui.activities.NewesDetailActivity;
import com.zigong.app.ui.activities.TYFOH5Activity;
import com.zigong.app.ui.adapter.CultureTravelAdapter;
import com.zigong.app.ui.adapter.CultureTravelAdapter;
import com.zigong.app.ui.adapter.GreatestAdapter;
import com.zigong.app.ui.util.IListShowData;
import com.zigong.app.ui.util.NewsDateComparator;
import com.zigong.app.ui.utils.CultureTravelDataAddHelper;
import com.zigong.app.ui.utils.GreatestDataAddHelper;
import com.zigong.app.ui.utils.MutilDateNewsGetHelper;
import com.zigong.app.ui.utils.UIUtils;
import com.zigong.app.utils.ListTypeUtils;
import com.zigong.app.utils.UserManager;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 文旅  栏目
 */
public class CultureTravelFragment extends ColumnBaseFragment implements CanRefreshLayout.OnRefreshListener
        , CanRefreshLayout.OnLoadMoreListener {

    @BindView(R.id.common_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;

    private CultureTravelDataAddHelper dataAddHelper;
    private CultureTravelAdapter adapter;
    private GroupOrderHelperSingled groupOrderHelper;

    private String hour24UrlTemp, bannerUrlTemp;
    private int current24Page = -1, secTitlePos = -1;
    private Date first24TitleDateTemp;

    private int newsFlashType = 0;
    private List<IListShowData> newsList = new ArrayList<>();
    private boolean isReset;
    private String news24Domain = "";
    private Handler handler;

    //    private LittleLifeManager littleLifeManager;

    private long lastGetTime = -1;
    private boolean isFirst = false;
    private boolean isShowLuZhou = false;
    private int newKey = CultureTravelAdapter.VIEWTYPE_NEWS;
    private boolean isRefresh = false;
    private long dyHeight = 0;
    private int newsIndex = 0;
    private int newsPageAll = 1;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_culture_travel, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onLoadMore() {
        if (newsIndex < newsPageAll - 1) {
            if (!getNewsList(CultureTravelAdapter.VIEWTYPE_NEWS, newsIndex + 1)) {
                dataAddHelper.removeUpItem(CultureTravelAdapter.VIEWTYPE_NEWS);
                Toast.makeText(getContext(), "获取更多失败", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        //首次加载数据，或之后下拉刷新
        getChannelList();
    }

    @Override
    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        groupOrderHelper = new GroupOrderHelperSingled();
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        refreshLayout.autoRefresh();

    }

    /**
     * 获取精选模块 多个类型的显示数据。
     */
    private void getChannelList() {
        if (TextUtils.isEmpty(channelUrl)) {
            toast("数据错误");
            JLog.e("int " + this.getClass().getSimpleName() + " url wrong ::" + channelUrl);
            refreshLayout.refreshComplete();
            return;
        }
        NetUtils.getNetAdapter().getChannelArray(getOwnerName(), channelUrl, new AbsListNetCallback<FocusColumn>(ListTypeUtils.FocusColums()) {
            @Override
            public void onSuc(List<FocusColumn> focusColumns) {
                if (ListUtils.isListValued(focusColumns)) {
                    resetUrlTemps();
                    for (FocusColumn fc : focusColumns) {
                        if (fc != null) {
                            switch (fc.getSubChannelType()) {
                                case CultureTravelAdapter.VIEWTYPE_BANNER:
                                    bannerUrlTemp = fc.getChannelUrl();
                                    break;
//                                case CultureTravelAdapter.VIEWTYPE_EXPRESS:
//                                    expressUrlTemp = fc.getChannelUrl();
//                                    break;
//                                case CultureTravelAdapter.VIEWTYPE_LIVE:
//                                    liveUrlTemp = fc.getChannelUrl();
//                                    break;
                                case CultureTravelAdapter.VIEWTYPE_NEWS:
                                    hour24UrlTemp = fc.getChannelUrl();
                                    break;
//                                case CultureTravelAdapter.VIEWTYPE_POPULAR:
//                                    popularUrlTemp = fc.getChannelUrl();
//                                    break;
                            }
                        }
                    }
                    if (dataAddHelper == null) {
                        dataAddHelper = new CultureTravelDataAddHelper();
                    }
                    lastGetTime = SystemClock.elapsedRealtime();

                    if (!getBannerArray(bannerUrlTemp, CultureTravelAdapter.VIEWTYPE_BANNER)) {
                        dataAddHelper.removeUpItem(CultureTravelAdapter.VIEWTYPE_BANNER);
                    }

                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                refreshLayout.refreshComplete();
            }
        });
    }

    /**
     * 获取 精选-banner数据
     *
     * @param url
     * @param mode
     * @return
     */
    private boolean getBannerArray(String url, final int mode) {
        if (TextUtils.isEmpty(url)) {
            JLog.e("int " + this.getClass().getSimpleName() + " url wrong ::" + url + "  mode=" + mode);
            return false;
        }
        if (!groupOrderHelper.addOne(mode)) {
            return false;
        }
        NetUtils.getNetAdapter().getNewsArray(getOwnerName(), url, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem(), mode) {//暂时使用calledIndex来保存mode
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                if (ListUtils.isListValued(newsItems)) {
                    HomeListItem hb = new HomeListItem();
                    hb.setNewsItemList(newsItems);
                    hb.setViewType(CultureTravelAdapter.VIEWTYPE_BANNER);
                    dataAddHelper.setUpDatas(getContext(), hb, CultureTravelAdapter.VIEWTYPE_BANNER);//暂时使用calledIndex来保存mode
                } else {
                    dataAddHelper.removeUpItem(calledIndex);//暂时使用calledIndex来保存mode
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                if (!getNewsList(CultureTravelAdapter.VIEWTYPE_NEWS, 0)) {
                    dataAddHelper.removeUpItem(CultureTravelAdapter.VIEWTYPE_NEWS);
                }

                onNetFinish(mode);//暂时使用calledIndex来保存mode
            }
        });
        return true;
    }

    /**
     * 获取 精选--视讯新闻数据
     *
     * @return
     */
    private boolean getNewsList(final int mode, final int index) {
        if (TextUtils.isEmpty(hour24UrlTemp)) {
            return false;
        }
        if (!groupOrderHelper.addOne(mode)) {
            return false;
        }
        NetUtils.getNetAdapter().getNewsPage(getOwnerName(), hour24UrlTemp, index, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem()) {
            @Override
            public void onSuc(List<NewsItem> newsItems) {
                newsPageAll = getPageResponse().getData().getPageAll();
                if (ListUtils.isListValued(newsItems)) {
                    newsIndex = index;
                    if (isRefresh) {
                        isReset = true;
                        newsList.clear();
                        newsList.addAll(newsItems);
                        dataAddHelper.addOrSet24Datass(getContext(), newsList, true);
                        isRefresh = false;
                    } else {
                        dataAddHelper.addOrSet24Datass(getContext(), newsItems, false);
                    }
                } else {
                    if (calledIndex <= 0) {
                        dataAddHelper.remove24data();
                        current24Page = calledIndex;
                    }
                }
            }

            @Override
            public void onEnd() {
                super.onEnd();
                if (newsIndex >= newsPageAll - 1) {
                    refreshLayout.setLoadMoreEnabled(false);
                } else {
                    refreshLayout.setLoadMoreEnabled(true);
                }
                onNetFinish(mode);//暂时使用calledIndex来保存mode
            }

            @Override
            public List<NewsItem> doInBackground(List<NewsItem> newsItems) {
                return super.doInBackground(newsItems);
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }
        });
        return true;
    }

    private void resetUrlTemps() {
        bannerUrlTemp = null;
        hour24UrlTemp = null;
        current24Page = -1;
        first24TitleDateTemp = null;
        secTitlePos = -1;
    }

    private synchronized void onNetFinish(int mode) {
        if (groupOrderHelper.removeOne(mode)) {
            refreshLayout.refreshComplete();
            refreshLayout.loadMoreComplete();
        }
        if (adapter == null && dataAddHelper.hasDatas()) {
            adapter = dataAddHelper.getAdapter(getContext());
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("页面", "首页"));
            pairs.add(new Pair<>("栏目", "精选"));
//            pairs.add(new Pair<>("行为类型", "点击"));
            adapter.setFragment(this);
            adapter.setPairs(pairs);
            recyclerView.setAdapter(adapter);
        }
        if (isReset) {
            isReset = false;
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    recyclerView.smoothScrollToPosition(0);
////                    recyclerView.scrollTo(0,0);
//                    layoutManager.scrollToPositionWithOffset(0,0);
                }
            }, 700);
        }
    }
}
